//
//  NearbyViewController.m
//  BaChat
//
//  Created by dllo on 16/6/15.
//  Copyright © 2016年 刘洋. All rights reserved.
//

#import "NearbyViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
//语音识别
#import "IflyTool.h"

//摇一摇
#import <CoreMotion/CoreMotion.h>

#define APIKey @"19f050897241dbae6bcec94adab45f93"
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width
#define ScreenHeight [[UIScreen mainScreen] bounds].size.height

//提出声明
@class PopupView;
@class IFlyDataUploader;
@class IFlySpeechRecognizer;


@interface NearbyViewController () <MAMapViewDelegate,AMapSearchDelegate,UITableViewDataSource, UITableViewDelegate,UIGestureRecognizerDelegate>
@property(nonatomic,strong)MAMapView *mapView;//地图对象属性

@property(nonatomic,strong)UIButton *locationButton;//开始定位的按钮

@property(nonatomic,strong)AMapSearchAPI *search;//搜索对象属性

@property(nonatomic,strong)CLLocation *currentlocation;//当前位置

@property (nonatomic, strong) CLGeocoder *geoC;//地理编码

@property (nonatomic, strong) UITableView *tableView;

//用在搜索周边饭馆的对象
@property (nonatomic, strong) NSArray *pois;

@property (nonatomic, strong) NSMutableArray *annotations;

//路线规划:首先声明一个长按手势===============
@property(nonatomic,strong)UILongPressGestureRecognizer *longPressGesture;//然后在attributes中进行初始化操作
//目的地坐标的antotion
@property(nonatomic,strong)MAPointAnnotation *destinationPoint;

//声明一个pathPolylines
@property(nonatomic,strong)NSArray *pathPolylines;


@property(nonatomic,strong)CLLocationManager *locationManager;
//========================

//长按手势
@property (nonatomic, strong)UILongPressGestureRecognizer *longPress;

@property (nonatomic, strong)UIButton *button;


@end

@implementation NearbyViewController

#pragma mark -懒加载
- (CLGeocoder *)geoC{
    
    if (!_geoC) {
        
        _geoC = [[CLGeocoder alloc]init];
//        [_geoC release];
    }
    
    return _geoC;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = YES;
    
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        self.locationManager = [[CLLocationManager alloc]init];
        if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.locationManager requestWhenInUseAuthorization];//iOS 8才有，且必须用上
        }
        
    }
    
    
    
    [self createMapView];
    [self initSearch];
    [self initAttributes];
    [self initLocationButton];
    [self initTableView];

}

#pragma mark -- 对象初始化
//初始化
- (void)initAttributes
{
    self.annotations = [NSMutableArray array];
    self.pois = nil;
    
    
    //初始化长按手势====================
    self.longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPress:)];
    self.longPressGesture.delegate = self;
    [self.mapView addGestureRecognizer:self.longPressGesture];
//    [self.longPressGesture release];
    
    
    
    
}

//长按手势对应button的点击方法==========================
-(void)handleLongPress:(UILongPressGestureRecognizer *)gesture
{NSLog(@"==============");
    if (gesture.state == UIGestureRecognizerStateBegan) {
        CLLocationCoordinate2D coordinate = [self.mapView convertPoint:[gesture locationInView:self.mapView] toCoordinateFromView:self.mapView];//刚开始的时候我们来获得地图上的坐标,并且把屏幕坐标转换成经纬度//下一步需要把这个经纬度记录下来,条件一个annotation,然后在搜索这个线路规划的时候把他记录的目的地坐标使用一下//所以现在我们要去属性那里添加一个目的地坐标的annotation
        //添加标注
        if (self.destinationPoint != nil) {//如果不为空我们就清理一下上一次的antation
            //清理
            [self.mapView removeAnnotation:self.destinationPoint];
            self.destinationPoint = nil;
            
        }
        //如果为空我们就进行一下初始化,并且把它加入到mapView的antation里面
        self.destinationPoint = [[MAPointAnnotation alloc]init];
        self.destinationPoint.coordinate = coordinate;
        self.destinationPoint.title = @"Destination";
        [self.mapView addAnnotation:self.destinationPoint];
        
    }
    //此处结束之后我们就需要进行路线规划的搜索请求了,那么首先我们家一个按钮
}




-(void)createMapView{
    //设置APIKey
    
    [AMapServices sharedServices].apiKey = APIKey;
    
    
  self.mapView = [[MAMapView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    
    self.mapView.delegate = self;
    //罗盘位置
    self.mapView.compassOrigin = CGPointMake(self.mapView.compassOrigin.x, 22);
    //比例尺位置
    self.mapView.scaleOrigin = CGPointMake(self.mapView.scaleOrigin.x, self.mapView.compassOrigin.y);
    [self.view addSubview:self.mapView];
    
    //打开用户定位
    self.mapView.showsUserLocation = YES;
    
    //设置跟踪模式
    [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    
}

//创建查询

/*!
 @brief 地址编码查询接 。
 @param request 查询选项。具体属性字段请参考 AMapGeocodeSearchRequest 类。
 - (void)AMapGeocodeSearch:(AMapGeocodeSearchRequest *)request;
 */

/*!
 @brief 逆地址编码查询接 。
 @param request 查询选项。具体属性字段请参考 AMapReGeocodeSearchRequest 类。
 - (void)AMapReGoecodeSearch:(AMapReGeocodeSearchRequest *)request;
 */
#pragma mark-- search
-(void)initSearch{
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
}


//当位置更新时，会进定位回调，通过回调函数，能获取到定位点的经纬度坐标
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    if (updatingLocation) {
//        NSLog(@"latitude : %f,longitude: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
//       
//        //
        
        self.currentlocation = [userLocation.location copy];
        
    }
}

//在选中用户位置annotation时弹出当前地址
-(void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
    // 选中定位annotation的时候进行逆地理编码查询
    if ([view.annotation isKindOfClass:[MAUserLocation class]]) {
        
        [self reGeoAction];
    }
    
    
}

//逆地理编码 发起搜索请求
-(void)reGeoAction{
    if (self.currentlocation) {
        AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc] init];
        request.location = [AMapGeoPoint locationWithLatitude:self.currentlocation.coordinate.latitude longitude:self.currentlocation.coordinate.longitude];
        [self.search AMapReGoecodeSearch:request];
    }
    
}

#pragma mark - AMapSearchDelegate
//逆地理编码
//搜索回调
//搜索失败
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error{
    
    NSLog(@"request : %@, error: %@", request, error);
    
}


//发出的要求是个request返回response=========================
//路线请求
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{
    
    if (response.count > 0)
    {
        
        [self.mapView removeOverlays:self.pathPolylines];
        self.pathPolylines = nil;
        
        
        // 只显示第一条
        _pathPolylines = [self polylinesForPath:response.route.paths[0]];
        [_mapView addOverlays:_pathPolylines];
        //调整地图显示范围
        [_mapView showAnnotations:@[_destinationPoint, _mapView.userLocation] animated:YES];
        
    }
    
    
}

-(CLLocationCoordinate2D *)coordinatesForString:(NSString *)string coordinateCount:(NSUInteger *)coordinateCount parseToken:(NSString *)token
{
    if (string == nil) {
        return NULL;
    }
    if (token == nil) {
        token = @",";
    }
    NSString *str = @"";
    if (![token isEqualToString:@","]) {
        str = [string stringByReplacingOccurrencesOfString:token withString:@","];
    }
    else{
        str = [NSString stringWithString:string];
        
    }
    NSArray *components = [str componentsSeparatedByString:@","];
    NSUInteger count = [components count] / 2;
    if (coordinateCount != NULL) {
        *coordinateCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D*)malloc(count * sizeof(CLLocationCoordinate2D));
    for (int i = 0; i < count; i++) {
        coordinates[i].longitude = [[components objectAtIndex:2*i] doubleValue];
        coordinates[i].latitude = [[components objectAtIndex:2 * i + 1]doubleValue];
    }
    
    return coordinates;
    
}

-(NSArray *)polylinesForPath:(AMapPath *)path{
    if (path == nil || path.steps.count == 0) {
        return nil;
    }
    NSMutableArray *polylines = [NSMutableArray array];
    //对每个step进行遍历,然后对每个step进行解析
    [path.steps enumerateObjectsUsingBlock:^(AMapStep *step, NSUInteger idx, BOOL * _Nonnull stop) {
        NSUInteger count = 0;
        
        //这事一个自己写的方法
        
        CLLocationCoordinate2D *coordinates = [self coordinatesForString:step.polyline coordinateCount:&count parseToken:@";"];
        
        MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
        [polylines addObject:polyline];
        free(coordinates),coordinates = NULL;
        
    }];
    
    return polylines;
}

//====================================================
//搜索成功
-(void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response{
    NSString *title = response.regeocode.addressComponent.city;
    if (title.length == 0) {
        title = response.regeocode.addressComponent.province;
    }
    
    
    self.mapView.userLocation.title = title;
    self.mapView.userLocation.subtitle = response.regeocode.formattedAddress;
    
}


- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    
    NSLog(@"request: %@", request);
    NSLog(@"response: %@", response);
    
    if (response.pois.count > 0)
    {
        self.pois = response.pois;
        
        [self.tableView reloadData];
        
        // 清空标注
        [self.mapView removeAnnotations:self.annotations];
        [self.annotations removeAllObjects];
    }
}



//
////在选中用户位置annotation时弹出当前地址
//-(void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
//    // 选中定位annotation的时候进行逆地理编码查询
//    if ([view.annotation isKindOfClass:[MAUserLocation class]]) {
//        
//        [self reGeoAction];
//    }
//    
//}


//创建定位按钮
-(void)initLocationButton{
    
    self.locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.locationButton.frame = CGRectMake( 10, 200, 35, 35);
   
    [self.locationButton addTarget:self action:@selector(locateAction) forControlEvents:UIControlEventTouchUpInside];
    [self.locationButton setImage:[UIImage imageNamed:@"location_yes"] forState:UIControlStateNormal];
    
    [self.view addSubview:self.locationButton];
    
    //search按钮
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    searchButton.frame = CGRectMake(ScreenWidth - 50,150, 35, 35);
//    //搜索按钮自动调整大小的方法(自动灵活右边距和上边距)
//    searchButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    
    searchButton.backgroundColor = [UIColor clearColor];
    
    [searchButton setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    
    [searchButton setTintColor:[UIColor blueColor]];
    [searchButton addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    self.button = searchButton;
    [self.view addSubview:searchButton];
    
    //长按手势
    self.longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureAction:)];
    
    [searchButton addGestureRecognizer:self.longPressGesture];
    
    
    
    
    //创建路线搜索请求按钮=======================================
    UIButton *pathButton = [UIButton buttonWithType:UIButtonTypeCustom];
    pathButton.frame = CGRectMake(ScreenWidth - 50, 200, 35, 35);
    pathButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
//    pathButton.backgroundColor = [UIColor whiteColor];
    
    [pathButton setImage:[UIImage imageNamed:@"path"] forState:UIControlStateNormal];
    
    [pathButton addTarget:self action:@selector(pathAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pathButton];
    //来实现pathAction的方法(就是发起这个请求)
    
}

//===============================================
-(void)pathAction{
    //如何判断是否发起了请求,首先得有出发点,有目的地,有search这个变量
    if (self.destinationPoint == nil || self.currentlocation == nil || self.search == nil) {
        NSLog(@"path search failed");
        return;//return必须写,防止崩溃
    }
    
    //反之.初始化一个请求
    AMapWalkingRouteSearchRequest *request1 = [[AMapWalkingRouteSearchRequest alloc] init];
    
    //出发点
    request1.origin = [AMapGeoPoint locationWithLatitude:self.currentlocation.coordinate.latitude longitude:self.currentlocation.coordinate.longitude];
    //目的地
    request1.destination = [AMapGeoPoint locationWithLatitude:self.destinationPoint.coordinate.latitude longitude:self.destinationPoint.coordinate.longitude];
    //搜索请求
    [self.search AMapWalkingRouteSearch:request1];//注意这句
    
}
//=============================
#pragma  mark - 定制标注视图（和原生地图定制方式类似）
//添加一个方法回调polyline=============================
-(MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay{
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        
        MAPolylineRenderer *polylineView = [[MAPolylineRenderer alloc]initWithOverlay:overlay];
        polylineView.strokeColor = [UIColor redColor];
        polylineView.lineWidth = 4;
        
        return polylineView;
        
        
    }
    return nil;
}


-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
    if (annotation == self.destinationPoint) {
        static NSString *reuseIndetifier = @"startAnnotationReuseIndetifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[MAPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        annotationView.canShowCallout = YES;
        annotationView.animatesDrop = YES;
        return annotationView;
        
    }
    
    //    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
    //        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
    //
    //    }
    
    
    
    //不定制自己位置标注的视图annotation---注解
    if ([annotation isKindOfClass:[MAUserLocation class]]) {
        return nil;//?????
    }
    
    //1.自带标注的视图
    MAPinAnnotationView *pinAnnView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"ID"];
    if (!pinAnnView) {
        pinAnnView = [[MAPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"ID"];
        //[pinAnnView release];//=========
    }
    // 是否可弹出视图
    pinAnnView.canShowCallout = YES;
    
    // 设置掉落动画
    pinAnnView.animatesDrop = YES;
    
    // 设置标注颜色
    
    pinAnnView.pinColor = MAPinAnnotationColorGreen;
    
    // 设置左视图
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    
    leftView.backgroundColor = [UIColor blueColor];
    
    pinAnnView.leftCalloutAccessoryView = leftView;
    
    //设置右视图
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    
    pinAnnView.rightCalloutAccessoryView = rightBtn;
    
    
    return pinAnnView;
    
    
}


- (void) longPressGestureAction: (UILongPressGestureRecognizer *) gesture
{     //长按开始
    if (gesture.state == UIGestureRecognizerStateBegan) {
        
        [[IflyTool shareTool] startRecognizer:^(IFlySpeechError *error, NSString *result) {
            
            if (error) {
                
                return ;
            }
            
            //高德带的POI搜索请求
            AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
            // [request release];//是否需要释放
        
            request.radius = 1000;
        
            //获取经纬度坐标
            request.location = [AMapGeoPoint locationWithLatitude:_currentlocation.coordinate.latitude longitude:_currentlocation.coordinate.longitude];
        
            request.keywords = [NSString stringWithFormat:@"%@",result];
            
            [_search AMapPOIAroundSearch:request];
            
            self.tableView.frame = CGRectMake(0, ScreenHeight / 3 * 2, ScreenWidth, ScreenHeight / 3);
            self.mapView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight / 3 * 2);
            
            self.button.selected = YES;
            
       }];
    }
    
}


#pragma mark - Helpers

//定位按钮的点击方法开启或关闭定位
-(void)locateAction{
    //userTrackingMode中有三种model (不追踪用户的位置更新,追踪,追踪位置和heading 的更新)
    
    if (self.mapView.userTrackingMode != MAUserTrackingModeFollow) {
        [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    }else{
        [self.mapView setUserTrackingMode:MAUserTrackingModeNone animated:YES];
        
    }
    
}



//替换定位按钮图标:使用mapView回调方法监听定位模式状态
-(void)mapView:(MAMapView *)mapView didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated{
    if (mode ==  MAUserTrackingModeNone) {
        //不追踪用户位置更新的情况下,按钮是关闭按钮
        [self.locationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    }else{
        //追踪的情况下按钮是开启状态
        [self.locationButton setImage:[UIImage imageNamed:@"location_yes"]forState:UIControlStateNormal];
        
    }
    
    
}

//search按钮的点击方法
//====================================================
- (void)searchAction:(UIButton *)button
{//此处有一个逻辑:如果点击了搜索按钮,则tebleView跳出来,否则全屏都是地图(在点击某处table回收)
    
    
    if (button.selected == NO) {
        
        [button setImage:[[UIImage imageNamed:@"search"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
 
        
        [UIView animateWithDuration:0.25 animations:^{
            
            [self.view layoutIfNeeded];
            self.tableView.frame = CGRectMake(0, ScreenHeight / 3 * 2, ScreenWidth, ScreenHeight / 3);
            
        }];
        
   
        
        
        
        
//    self.mapView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight / 3 * 2);
 
    //如果当前位置为空,并且没有搜索
    if (_currentlocation == nil || _search == nil)
    {
        NSLog(@"search failed");
        return;
    }
    //高德带的POI搜索请求
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    // [request release];//是否需要释放
    
    request.radius = 1000;
    NSLog(@"获取商店位置");
    //获取经纬度坐标
    request.location = [AMapGeoPoint locationWithLatitude:_currentlocation.coordinate.latitude longitude:_currentlocation.coordinate.longitude];
    //这崩了
    NSLog(@"获取名字成功");
    
    request.keywords = @"餐饮 | 银行 | 公司 | 娱乐 | 公园 | 市场 | 酒店" ;
    
    [_search AMapPOIAroundSearch:request];
        
    }else{
        
       
        button.backgroundColor = [UIColor clearColor];
        
        
        [UIView animateWithDuration:0.25 animations:^{
            
            [self.view layoutIfNeeded];
      
            self.tableView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, ScreenHeight / 3);
        }];
 
        self.mapView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight );
    }
    
    button.selected = !button.selected;
    
}

//======================================================================
//tableView和地图布局大小分布的方法
- (void)initTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,ScreenHeight ,ScreenWidth,ScreenHeight / 3 ) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
}

#pragma mark - UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    
    //通过POI所搜的所有对象赋值给pois
    AMapPOI *poi = _pois[indexPath.row];
    //每一个cell的名称就是pois的名字
    cell.textLabel.text = poi.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ 距离:%ld米", poi.address, (long)poi.distance];
    //
    //cell.textLabel.text = @"11111";
    return cell;
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{//cell的数量就是pois里面的数量
    return _pois.count;
    
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 为点击的poi点添加标注
    AMapPOI *poi = _pois[indexPath.row];
    
    MAPointAnnotation *pointAnn = [[MAPointAnnotation alloc] init];
    pointAnn.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
    
    pointAnn.title =poi.name;
    pointAnn.subtitle = [NSString stringWithFormat:@"%@ 距离:%ld米", poi.address, (long)poi.distance];
    
    
    
    [self.mapView addAnnotation:pointAnn];
    
    [self.annotations addObject:pointAnn];
}


- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{

    
    self.navigationController.navigationBarHidden = NO;

    [self.navigationController popViewControllerAnimated:YES];
}

@end
